package com.yaozheng.vocationaltraining.fragment.exam;

import android.content.Intent;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.PKPlayerStatusAdapter;
import com.yaozheng.vocationaltraining.bean.PKPlayerStatusBean;
import com.yaozheng.vocationaltraining.bean.PKRoomBean;
import com.yaozheng.vocationaltraining.bean.PlayerBean;
import com.yaozheng.vocationaltraining.bean.SeatBean;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.iview.IPKConfirmView;
import com.yaozheng.vocationaltraining.service.exam.PKConfirmService;
import com.yaozheng.vocationaltraining.service.impl.exam.PKConfirmServiceImpl;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

/**
 * Created by moon on 2017/11/16.
 */

@EFragment(R.layout.activity_pk_confirm)
public class PKConfirmFragment extends BaseFragment
        implements IPKConfirmView {

    @ViewById
    ListView listView;
    PKPlayerStatusAdapter pkPlayerStatusAdapter;
    ArrayList<PKPlayerStatusBean> pkPlayerStatusData = new ArrayList<>();

    @ViewById
    TextView headTitleText;

    @ViewById
    Button start_button;
    @ViewById
    Button leave_button;

    @ViewById
    TextView playerLimit_textview;

    @ViewById
    LinearLayout not_ready_layout;
    @ViewById
    TextView ready_layout;

    @Bean(PKConfirmServiceImpl.class)
    PKConfirmService pkConfirmService;

    private BitmapLoader userBitmapLoader;
    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }

    public PKHallFragment getPkHallFragment() {
        return pkHallFragment;
    }

    public void setPkHallFragment(PKHallFragment pkHallFragment) {
        this.pkHallFragment = pkHallFragment;
    }

    PKHallFragment pkHallFragment;

    public int getRoomId() {
        return roomId;
    }

    public void setRoomId(int roomId) {
        this.roomId = roomId;
    }

    int roomId;

    public int getSeatId() {
        return seatId;
    }

    public void setSeatId(int seatId) {
        this.seatId = seatId;
    }

    int seatId;

    public int getPlayerLimit() {
        return playerLimit;
    }

    public void setPlayerLimit(int playerLimit) {
        this.playerLimit = playerLimit;
    }

    int playerLimit;
    Integer gameId;

    @AfterViews
    public void initView() {
        headTitleText.setText("比赛确认");
        pkConfirmService.init(this);
        userBitmapLoader = new BitmapLoader(Glide.with(this), R.drawable.user_img);


        playerLimit_textview.setText(playerLimit+"");

        pkPlayerStatusAdapter = new PKPlayerStatusAdapter(this.getActivity()
                ,pkPlayerStatusData);
        listView.setAdapter(pkPlayerStatusAdapter);

        not_ready_layout.setVisibility(View.VISIBLE);
        ready_layout.setVisibility(View.GONE);


        onRefresh();
    }

    private void onRefresh() {
        pkConfirmService.list(roomId);
    }


    @Click(R.id.start_button)
    public void startButtonClick() {//
        pkConfirmService.start(seatId);
    }

    @Click(R.id.leave_button)
    public void leaveButtonClick() {//打开排行榜界面
        pkConfirmService.leave(seatId);
        this.getFragmentManager().popBackStack();
    }



    @Override
    public boolean backPressed() {
        if (not_ready_layout.getVisibility() == View.VISIBLE) { //未准备状态
            pkConfirmService.leave(seatId);
            return super.backPressed();
        } else {
            pkConfirmService.leave(seatId);
            not_ready_layout.setVisibility(View.VISIBLE);
            ready_layout.setVisibility(View.GONE);
            return false;
        }
    }


    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","room","seats");
            JSONObject gameObject = TypeUtils.getJsonObject(jsonObject,"data","room");
            gameId = TypeUtils.getJsonInteger(gameObject,"gameId");
            if (dataList != null) {
                pkPlayerStatusData.clear();

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject playerJsonObject = dataList.getJSONObject(i);
                    PKPlayerStatusBean bean = new PKPlayerStatusBean();
                    bean.setId(playerJsonObject.getInt("id"));
                    bean.setRoomId(playerJsonObject.getInt("roomId"));
                    bean.setPlayerId(playerJsonObject.getInt("playerId"));
                    bean.setPlayerStatus(playerJsonObject.getInt("playerStatus"));
                    bean.setStartTime(playerJsonObject.getString("startTime"));
                    bean.setPlayerName(playerJsonObject.getString("playerName"));
                    bean.setPlayerAvatar(playerJsonObject.getString("playerAvatar"));

                    pkPlayerStatusData.add(bean);
                }

                if (isAllReady()){
                    if (cdt != null){
                        cdt.cancel();
                    }
                    if (gameId != null && gameId > 0){
                        showOperatingProgressDialog("获取试卷中...");
                        pkConfirmService.loadQuestionList(
                                gameId);
                    }else {
                        Toast.makeText(PKConfirmFragment.this.getActivity(),
                                "gameId为空",Toast.LENGTH_SHORT).show();
                    }

                }
                    pkPlayerStatusAdapter.setData(pkPlayerStatusData);
                    pkPlayerStatusAdapter.notifyDataSetChanged();





            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    private boolean isAllReady(){
        if(pkPlayerStatusData == null || pkPlayerStatusData.size() < playerLimit){
            return false;
        }
        for (PKPlayerStatusBean bean : pkPlayerStatusData){
            if(bean.getPlayerStatus() == 0){ //有未完成的
                return false;
            }
        }
        return true;
    }


    @UiThread
    @Override
    public void responseError(String error) {
//        由于长时间没有准备，您已经被系统踢出房间
        Toast.makeText(getHomeActivity(),error,Toast.LENGTH_SHORT).show();
        getHomeActivity().backClick();
    }


    @UiThread
    @Override
    public void leaveSeatSuccess(JSONObject jsonObject) {
        if(jsonObject.getInt("error_code") == 0){
//            Toast.makeText(this.getActivity(),"离开成功"
//                    ,Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this.getActivity(),
                    jsonObject.getString("error_msg"),Toast.LENGTH_SHORT).show();
        }
        if (pkHallFragment != null){
            pkHallFragment.onRefresh();
        }
        //getHomeActivity().backClick();
    }

    @UiThread
    @Override
    public void leaveSeatError(String error) {
        //Toast.makeText(this.getActivity(),error,Toast.LENGTH_SHORT).show();
    }

    CountDownTimer cdt;
    @UiThread
    @Override
    public void startPKSuccess(JSONObject jsonObject) {
        not_ready_layout.setVisibility(View.GONE);
        ready_layout.setVisibility(View.VISIBLE);

        onRefresh();

        cdt = new CountDownTimer(60000 * 3, 1000 * 5) {
            @Override
            public void onTick(long millisUntilFinished) {
                onRefresh();
            }
            @Override
            public void onFinish() {

            }
        };

        cdt.start();
    }

    @UiThread
    @Override
    public void startPKError(String error) {

    }

    @UiThread
    @Override
    public void getQuestionListSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        JSONObject paperJsonObject = TypeUtils.getJsonObject(jsonObject,
                "data", "game","paper");
        if(!paperJsonObject.containsKey("duration")){
            paperJsonObject.put("duration",TypeUtils.getJsonObject(jsonObject,
                    "data", "game").getInt("duration"));
        }
        // 进入考试
        Intent intent = getBaseActivity().getIntent();
        intent.putExtra("examType", "8");//8表示PK赛
        intent.putExtra("paperId",
                TypeUtils.getJsonInteger(paperJsonObject, "id"));
        intent.putExtra("startTimeLong", System.currentTimeMillis());
        intent.putExtra("paperJsonObjectStr", paperJsonObject.toString());
        intent.putExtra("examTitle", "PK赛");
        intent.putExtra("gameId",gameId);
        getHomeActivity().openOnlineExamFragment();
    }

    @UiThread
    @Override
    public void getQuestionListError(String error) {
        Toast.makeText(this.getActivity(),error,Toast.LENGTH_SHORT).show();
    }
}
